package com.johnson.news.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.johnson.news.BR;
import com.johnson.news.R;
import com.johnson.news.databinding.ActivityNewsDetailBinding;
import com.johnson.news.event_msg.CollectStatusChangedMsg;
import com.johnson.news.model.bean.BaseResponseData;
import com.johnson.news.model.bean.ContinueView;
import com.johnson.news.model.bean.NewsContent;
import com.johnson.news.model.bean.NewsItem;
import com.johnson.news.model.bean.NewsReplyItem;
import com.johnson.news.model.remote.RemoteDataSource;
import com.johnson.news.model.util.NewsPreference;
import com.johnson.news.share.SharePopupWindow;
import com.johnson.news.util.Utils;
import com.youmbe.library.BaseBindingActivity;
import com.youmbe.library.BaseRecyclerAdapter;
import com.youmbe.library.util.MyToast;
import com.youmbe.library.util.SerializeUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

public class NewsDetailActivity extends BaseBindingActivity<ActivityNewsDetailBinding> {

    public static final String intent_key_from_push = "intent_key_from_push";
    public static final String intent_key_is_hot = "intent_key_is_hot";
    public static final String intent_key_mid = "intent_key_mid";

    NewsItem item;
    NewsContent newsContent;

    boolean isHotNews, isFromPush;
    String mid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isHotNews = getIntent().getBooleanExtra(intent_key_is_hot, false);
        isFromPush = getIntent().getBooleanExtra(intent_key_from_push, false);
        mid = getIntent().getStringExtra(intent_key_mid);
        item = (NewsItem) getIntent().getParcelableExtra("data");
        if(TextUtils.isEmpty(mid)) {
            if(!TextUtils.isEmpty(item.getMid()))
                mid = item.getMid();
            else
                mid = Utils.MID;
        }
        super.onCreate(savedInstanceState);

    }

    boolean isOnPause;
    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (dataBinding.detailContent != null) {
                dataBinding.detailContent.getClass().getMethod("onPause").invoke(dataBinding.detailContent, (Object[]) null);
                isOnPause = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当Activity执行onResume()时让WebView执行resume
     */
    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (dataBinding.detailContent != null) {
                    dataBinding.detailContent.getClass().getMethod("onResume").invoke(dataBinding.detailContent, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    BaseRecyclerAdapter<NewsItem> adapter;
    BaseRecyclerAdapter<NewsReplyItem> replyAdapter;

    @Override
    protected void init() {
//        dataBinding.setData(item);

        if(!isHotNews && isFromPush) {
            dataBinding.detailOtherTitle.setVisibility(View.GONE);
            dataBinding.detailOtherList.setVisibility(View.GONE);
            dataBinding.detailReplyList.setVisibility(View.GONE);
            dataBinding.detailReplyTitle.setVisibility(View.GONE);
            dataBinding.newsBottomLayout.setVisibility(View.GONE);
        }

        //暂时不显示评论
        dataBinding.detailReplyList.setVisibility(View.GONE);
        dataBinding.detailReplyTitle.setVisibility(View.GONE);
        //暂时不显示评论

        adapter = new BaseRecyclerAdapter<>(this, R.layout.adapter_news, com.johnson.news.BR.data);
        dataBinding.detailOtherList.setAdapter(adapter);
        dataBinding.detailOtherList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.detailOtherList.setNestedScrollingEnabled(false);

        adapter.setBindingViewClickListener(BR.onClickListener, onClickListener);

        replyAdapter = new BaseRecyclerAdapter<>(this, R.layout.adapter_news_reply_list, BR.data);
        dataBinding.detailReplyList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.detailReplyList.setNestedScrollingEnabled(false);
        dataBinding.detailReplyList.setAdapter(replyAdapter);
        dataBinding.detailReplyList.setPullRefreshEnabled(false);
        dataBinding.detailReplyList.setLoadingMoreEnabled(true);
        dataBinding.detailReplyList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                getReplies();
            }
        });


        dataBinding.detailContent.setVerticalScrollBarEnabled(false);
        dataBinding.detailContent.setHorizontalScrollBarEnabled(false);
        dataBinding.detailContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        dataBinding.detailContent.getSettings().setJavaScriptEnabled(true);
        dataBinding.detailContent.getSettings().setSupportZoom(false);
        dataBinding.detailContent.getSettings().setBuiltInZoomControls(false);
        dataBinding.detailContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        dataBinding.detailContent.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                Intent intent = new Intent(activityInstance, WebViewActivity.class);
                intent.putExtra(WebViewActivity.intent_key_url, url);
                startActivity(intent);
                return true;
            }
        });
//        dataBinding.detailContent.getSettings().setTextZoom(88);

        dataBinding.setOnClickListener(onClickListener);

        getData();
    }

    void getData() {
        RemoteDataSource.getRemoteDataSource()
                .getNewsDetail(activityInstance, mid, item.getCatid(), item.getItemid())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                }).subscribe(new Consumer<NewsContent>() {
            @Override
            public void accept(NewsContent newsContent) throws Exception {
                newsContent.collected = Utils.hasCollectedNews(activityInstance, newsContent.getItemid());
                newsContent.liked = Utils.hasLikedNews(activityInstance, newsContent.getItemid());

                item.setTitle(newsContent.getTitle());
                item.setAddtime(newsContent.getAddtime());
                item.setCatname(newsContent.getCatname());
                item.setThumb(newsContent.getThumb());
                item.setHits(newsContent.getHits());

                NewsDetailActivity.this.newsContent = newsContent;
                dataBinding.setData(newsContent);

//                dataBinding.detailContent.loadDataWithBaseURL(newsContent.hlink, null, "text/html", "utf-8", null);//newsContent.getContent()

                dataBinding.detailContent.loadUrl(newsContent.hlink);

                if(!isHotNews) {
                    getRelatedNews();
                } else
                    dataBinding.detailOtherTitle.setVisibility(View.GONE);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

//        getReplies();//暂不显示回复列表
    }

    int replyPageIndex = 0;
    void getReplies() {
        replyPageIndex++;
        RemoteDataSource.getRemoteDataSource()
                .getNewsReplies(mid, item.getItemid(), 10, replyPageIndex)
                .subscribe(new Consumer<ArrayList<NewsReplyItem>>() {
                    @Override
                    public void accept(ArrayList<NewsReplyItem> newsReplyItems) throws Exception {
                        if(newsReplyItems != null && newsReplyItems.size() > 0)
                            replyAdapter.addData(newsReplyItems);
                    }
                });

    }

    void getRelatedNews() {
        RemoteDataSource.getRemoteDataSource()
                .getNewsRelatedList(mid, item.getCatid(), 4, 1)
                .subscribe(new Consumer<ArrayList<NewsItem>>() {
                    @Override
                    public void accept(ArrayList<NewsItem> continueViews) throws Exception {
                        adapter.setData(continueViews);
                        if(continueViews.size() == 0)
                            dataBinding.detailOtherTitle.setVisibility(View.GONE);
                        else
                            dataBinding.detailOtherTitle.setVisibility(View.VISIBLE);
                    }
                });
    }

//    boolean checkLogin() {
//        if(!NewsPreference.getinstance(activityInstance).getLoginState()) {
//            MyToast.showToast("您还没有登录", activityInstance);
//            startActivity(LoginActivity.class, null);
//            return false;
//        }
//        return true;
//    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.news_layout:
                    Object object = view.getTag(R.id.adapter_tag_data);
                    if(object != null && object instanceof NewsItem) {
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("data", (NewsItem) object);//((ContinueView) object).toNewsItem()
                        startActivity(NewsDetailActivity.class, bundle);
                    }
                    break;
                case R.id.news_collect:
                    if (newsContent == null)
                        return;
//                    if(checkLogin()) {
                        newsContent.collected = !newsContent.collected;
                        dataBinding.setData(newsContent);

                        Utils.updateNewsStatus(activityInstance, item, newsContent.liked, newsContent.collected);

                        EventBus.getDefault().post(new CollectStatusChangedMsg());
//                    }
                    break;
                case R.id.news_share:
                    if(newsContent != null) {
                        HashMap<String, String> shareMap = new HashMap<>();
                        shareMap.put("title", newsContent.getTitle());
                        shareMap.put("content", newsContent.getIntroduce());
                        shareMap.put("url", newsContent.getLink());
                        shareMap.put("thumb", newsContent.getThumb());
                        SharePopupWindow sharePopupWindow = new SharePopupWindow(activityInstance, shareMap);
                        sharePopupWindow.setOnShareSuccessListener(new SharePopupWindow.ShareSuccess() {
                            @Override
                            public void OnShareSuccess() {
                                MyToast.showToast(("分享成功"), activityInstance);
                            }
                        });
                        sharePopupWindow.showAtLocation(dataBinding.getRoot(), Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
                    }
                    break;
                case R.id.news_reply:
//                    if(checkLogin()) {
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("data", item);
                        startActivity(NewsPostReplyActivity.class, bundle);
//                    }
                    break;
                case R.id.news_like:
//                    if(checkLogin()) {
                        if (newsContent == null)
                            return;
                        if(Utils.hasLikedNews(activityInstance, newsContent.getItemid())) {
                            MyToast.showToast("您已点赞过该文章", activityInstance);
                            return;
                        }
                        RemoteDataSource.getRemoteDataSource()
                                .newsLike(newsContent.getItemid(), NewsPreference.getinstance(activityInstance).getLoginName())
                                .subscribe(new Consumer<BaseResponseData>() {
                                    @Override
                                    public void accept(BaseResponseData baseResponseData) throws Exception {
                                        if (baseResponseData.status == 1) {
                                            newsContent.setZan(newsContent.getZan() + 1);
                                            newsContent.liked = true;
                                            dataBinding.setData(newsContent);

                                            Utils.updateNewsStatus(activityInstance, item, newsContent.liked, newsContent.collected);
                                        } else {
                                            MyToast.showToast(baseResponseData.msg, activityInstance);
                                        }
                                    }
                                });
//                    }
                    break;
                case R.id.follow_weibo:
                    startActivity(OfficialWeiboActivity.class, null);
                    break;
                case R.id.follow_weixin:
                    startActivity(OfficalWeiXinActivity.class, null);
                    break;
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_news_detail;
    }
}
